package org.net.cms.controller.admin.parentaccount;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import jakarta.annotation.security.PermitAll;
import org.net.cms.config.Result;
import org.net.cms.service.parentaccount.ParentAccountService;
import org.net.cms.uitl.JwtUtil;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/admin/account")
@Tag(name = "管理后台 - 家长账号管理")
public class ParentAccountController {

    @Resource
    private ParentAccountService parentAccountService;

    @Resource
    private AuthenticationManager authenticationManager;

    @PostMapping("/login")
    @Operation(summary = "后台登录", description = "后台登录")
    public Result login(@RequestParam String username, @RequestParam String password) {
        JwtUtil jwtUtil = new JwtUtil();
        UsernamePasswordAuthenticationToken auth = new UsernamePasswordAuthenticationToken(username, password);
        Authentication authentication = authenticationManager.authenticate(auth);
        SecurityContextHolder.getContext().setAuthentication(authentication);
        UserDetails userDetails = (UserDetails) authentication.getPrincipal();
        return Result.success(jwtUtil.getToken(userDetails.getUsername()));
    }

    @PostMapping("/update")
    @Operation(summary = "删除家长账号", description = "根据 ID 删除家长账号（软删除）")
    public Result delete(int id) {
        parentAccountService.deleteParentAccountDto(id);
        return Result.success();
    }

    @GetMapping("/get")
    @Operation(summary = "查询家长账号详情", description = "根据 ID 获取家长账号详情")
    public Result getById(int id) {
        return Result.success(parentAccountService.getParentAccountDto(id));
    }

    @GetMapping("/list")
    @Operation(summary = "查询列表", description = "获取所有未删除的家长账号列表")
    public Result list() {
        return Result.success(parentAccountService.parentAccountList());
    }

    @GetMapping("/resume")
    @Operation(summary = "恢复默认密码")
    @Parameter(name = "id", description = "用户id", required = true)
    public Result resumePassword(int id) {
        parentAccountService.resumePassword(id);
        return Result.success("恢复成功");
    }
}
